﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CloudSoft.Extensions;

namespace ERPStore.Exporter.Models.LeadSources
{
	public class LeGuideSource : ERPStore.Models.LeadSourceBase
	{
		public override string Id
		{
			get { return "EE1ECED1-A717-4c52-91C5-11E59DDED59C"; }
		}

		public override string Name
		{
			get { return "LeGuide"; }
		}

		public override string Description
		{
			get { return "Moteur de comparaison LeGuide"; }
		}

		public override string TrackSourceId
		{
			get { return "leguide"; }
		}

		public override string Medium
		{
			get { return "cpc"; }
		}

		public override ERPStore.Models.LeadSourceType LeadSourceType
		{
			get { return ERPStore.Models.LeadSourceType.PriceComparator; }
		}

		public override bool Match(Uri sourceUri, Uri landingUri, out string keywords, out string subHost, out decimal amount)
		{
			subHost = null;
			amount = 0;
			var landingPrms = landingUri.GetParameters();
			var sourcePrms = sourceUri.GetParameters() ?? new System.Collections.Specialized.NameValueCollection();
			keywords = Uri.UnescapeDataString(sourcePrms["ms"] ?? string.Empty);
			keywords = keywords.Replace("+", " ");

			if (landingPrms.AllKeys.Contains("gclid")) // Lien sponso 
			{
				return false;
			}
			else if (landingPrms.AllKeys.Contains("estid"))
			{
				var estid = landingPrms["estid"];
				if (estid.Equals(TrackSourceId, StringComparison.InvariantCultureIgnoreCase))
				{
					subHost = "No referer";
					amount = 0.17m;

					if (sourceUri.Host.ToLower().IndexOf("choozen") != -1)
					{
						subHost = "choozen";
						var match = System.Text.RegularExpressions.Regex.Match(sourceUri.PathAndQuery, @"(gs|ts)-(?<kw>[^~]+)(~|\.)");
						if (match.Success)
						{
							keywords = (match.Groups["kw"].Value ?? string.Empty).Replace("-", "");
							keywords = Uri.UnescapeDataString(keywords ?? string.Empty);
							keywords = keywords.Replace("+", " ");
						}
					}

					return true;
				}
			}
			else if (sourceUri.Host.ToLower().IndexOf("leguide") != -1)
			{
				subHost = "leguide/free";
				return true;
			}
			else if (sourceUri.Host.ToLower().IndexOf("webmarchand") != -1)
			{
				subHost = "WebMarchand";
				return true;
			}

			return false;
		}
	}
}
